package com.b511.swpu.cementbackend.config.sercurity;

import com.b511.swpu.cementbackend.entity.SysUser;
import com.b511.swpu.cementbackend.util.enumeration.Code;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class TokenAuthenticationFilter extends OncePerRequestFilter {

    private final static String PUBLIC_URL = "/public/login";

    private final static String DEV_URL = "/dev";

    // 6.8 与主数据交互数据，不用认证
    private final static String RECEIVE_URL = "/dataReceive";

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String requestUri = httpServletRequest.getRequestURI();
        boolean hasExcludeUrl = requestUri.contains(PUBLIC_URL) || requestUri.contains(DEV_URL) || requestUri.contains(RECEIVE_URL);
        boolean isAuthenticated = authentication == null || !authentication.isAuthenticated();
        if (!hasExcludeUrl && isAuthenticated) {
            String token = httpServletRequest.getHeader("Authorization");
            if (!StringUtils.hasText(token)) {
                throw new BadCredentialsException(Code.ILLEGAL.getMsg());
            }
            context.setAuthentication(new SysUser().setToken(token).setUrl(requestUri));
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
